var app = getApp();
var util = require('../../utils/util.js')
var WxParse = require('../../utils/wxParse/wxParse.js');
var Bmob = require('../../utils/Bmob-2.2.0.min.js');
Page({
  data: {
    goodsId: '',
    goodsInfo: {},
    modelStrs: {},
    selectModelInfo: {
      models: [],
      stock: '',
      price: '',
      virtualPrice: '',
      buyCount: 1,
      models_text : ''
    },
    pageQRCodeData:{
      shareDialogShow: "100%",
      shareMenuShow: false,
    },
    commentArr: [],
    commentNums: [],
    commentExample: '',
    commentPage: 1,
    commnetType: 0,
    commentTotalPage: '',
    defaultPhoto: '',
    allStock: '',
    highPrice:0,
    lowPrice:0,
    seckill_highPrice:0,
    seckill_lowPrice:0,
    addToShoppingCartHidden: true,
    ifAddToShoppingCart: true,
    priceDiscountStr: '',
    page_hidden: false,
    appointmentPhone:'15877310350',
    detailCommetType: 'detail',
    carouselCurrentIndex: 1,
    imageOrVideo: 'image',
    videoPlay: false
  },


  onLoad: function(options){
    console.log(options);
    var goodsId = options.detail || decodeURIComponent(options.scene),
        contact = options.contact || '',
        franchiseeId = options.franchisee || '',
        cartGoodsNum = options.cart_num || 0,
        defaultPhoto = app.getDefaultPhoto(),
        goodsType = options.goodsType || 0,
        userToken = options.user_token || '',
        hidestock = options.hidestock || '',
        isShowVirtualPrice = options.isShowVirtualPrice || '';
    this.setData({
      goodsId: goodsId,
      contact: contact,
      defaultPhoto: defaultPhoto,
      franchiseeId: franchiseeId,
      cartGoodsNum: cartGoodsNum,
      goodsType : goodsType,
      
     
      hidestock : hidestock == 'true' ? true : false,
      isShowVirtualPrice: isShowVirtualPrice == 'true' ? true : false
    })
    this.dataInitial();
    //推广存储user_token
    if(userToken){
      app.globalData.PromotionUserToken = userToken;
    }
    this.videoContext = wx.createVideoContext('goodsDetail-video');
  },
  onReachBottom: function(){
    if (this.data.detailCommetType == 'comment' && this.data.commentPage <= this.data.commentTotalPage){
     this.getAssessList(this.data.commentType, this.data.commentPage, 1);
    }
  },

  dataInitial: function () {
    var that = this;

    var data_id = this.data.goodsId;
    var sub_shop_app_id = this.data.franchiseeId;
  
    var goods =  Bmob.Query("goods"); 
   
    goods.include("FranchiseeId");
    goods.get(data_id).then(res=>{
      that.modifyGoodsDetail(res)
    
    })
  
  },

  showCouponVerify: function () {
    var that = this;
    var qr_url = that.data.goodsInfo.qr_code;
    var goodId = that.data.goodsId;
    var path = "pages/goodsDetail/goodsDetail";
    that.get_qrcode(path, goodId, goodId, qr_url);
  },
  //保存小程序码
  saveqrcode: function (qrcodeUrl, goodId) {
    var GoodInfo = Bmob.Object.extend("goods");
    var goodInfo = new GoodInfo();
    goodInfo.get(goodId, {
      success: function (res) {
        res.set('qrcodeUrl', qrcodeUrl);
        res.save();
      },
      error: function (object, error) {
        return false;
      }

    })



  },
  //获取小程序码
  get_qrcode: function (path, qrtext, Id, qr_Url) {

    var that = this;
    var width = 430;
    if (typeof (qr_url) == 'undefined' || typeof (qr_url) == 'null' || qr_url.length == 0) {
      Bmob.generateCode({
        "path": path, "scene":Id, "interface": "b", "width": width, "type": 1
      }).then(function (obj) {
         console.log("qrtext")
        that.saveqrcode(Id, obj.url);
        
       

        /* 
         wx.downloadFile({
           url: url, //仅为示例，并非真实的资源
           success: function (res) {
             // 只要服务器有响应数据，就会把响应内容写入文件并进入 success 回调，业务需要自行判断是否下载到了想要的内容
             console.log(res);
             if (res.statusCode === 200) {
 
               that.draw_QRpic(filePath, text, price, id, res.tempFilePath);
               that.save_qrcode(obj.url)
             }
           }
         })*/

      }, function (err) {
        console.log(err);
      });
    } else {

      this.setData({
        'detailShow': false,
        'verifyShow': true,
        'verifyData.qrcodeUrl': qr_url
      });
      /*
      qr_url = qr_url.replace(/b0.upaiyun/, "bmobcloud")
      qr_url = qr_url.replace(/http/, "https")
      wx.downloadFile({
        url: qr_url, //仅为示例，并非真实的资源
        success: function (res) {
          // 只要服务器有响应数据，就会把响应内容写入文件并进入 success 回调，业务需要自行判断是否下载到了想要的内容

          if (res.statusCode === 200) {
            qr_url: res.tempFilePath;
            //that.draw_QRpic(filePath, text, price, id, res.tempFilePath)
          }
        }
      })*/

    }

  }

  ,
  onShareAppMessage1: function(){
    this.setData({
      pageQRCodeData: {
        shareDialogShow: "100%",
        shareMenuShow: false,
      }
    })
    let that = this,
        goodsId = this.data.goodsId,
        contact = this.data.contact,
        franchiseeId = this.data.franchiseeId,
        cartGoodsNum = this.data.cart_num || '',
        isSeckill = this.data.isSeckill,
        title = this.data.goodsInfo.title,
        urlSeckill = isSeckill ? '&goodsType=seckill' : '',
        urlPromotion = app.globalData.PromotionUserToken ? '&user_token=' + app.globalData.PromotionUserToken : '',
      path = '/pages/goodsDetail/goodsDetail?detail=' + goodsId + '&contact=' + contact + (franchiseeId ? '&franchisee=' + franchiseeId + '&cart_num=' + cartGoodsNum : '') + urlSeckill + urlPromotion;

    return app.shareAppMessage({
      path: path,
      title: title,
      success: function (addTime) {
        app.showToast({ title: '转发成功', duration: 500 });
        // 转发获取积分
    
      }
    });
  },
  onUnload: function () {
    if(this.downcount){
      this.downcount.clear();
    }
  },
  goToMyOrder: function(){
    var franchiseeId = this.data.franchiseeId,
      pagePath = '/pages/myOrder/myOrder'+(franchiseeId ? '?franchisee='+franchiseeId : '');
    app.turnToPage(pagePath, true);
  },
  goToShoppingCart: function(){
    var franchiseeId = this.data.franchiseeId,
      pagePath = '../shoppingCart/shoppingCart'+(franchiseeId ? '?franchisee='+franchiseeId : '');
    app.turnToPage(pagePath, true);
  },
  goToHomepage: function(){
    let that = this;
    if (that.data.franchiseeId){
      let pages = getCurrentPages();
      let url = '/franchisee/pages/franchiseeDetail/franchiseeDetail';
      let delta = 1;
      for (let i = pages.length - 1; i >= 0; i--){
        let page = pages[i];
        if (page.route == url && page.options.detail == that.data.franchiseeId){
          delta = pages.length - 1 - i;
          app.turnBack({delta: delta});
          return;
        }
      }
      app.turnToPage('/franchisee/pages/franchiseeDetail/franchiseeDetail?detail=' + that.data.franchiseeId, true);
    }else{
      var router = app.getHomepageRouter();
      app.reLaunch({url: '/pages/'+router+'/'+router});
    }
  },
  goToCommentPage: function(){
    var franchiseeId = this.data.franchiseeId,
      pagePath = '/eCommerce/pages/goodsComment/goodsComment?detail='+this.data.goodsId+(franchiseeId ? '&franchisee='+franchiseeId : '');
    app.turnToPage(pagePath);
  },
  makeAppointment: function () {
    var franchiseeId = this.data.franchiseeId,
      unitTime = this.data.modelStrs[0] && this.data.modelStrs[0].substring(this.data.modelStrs[0].length - 1),
      unitType = unitTime == '分' ? 1 : (unitTime == '时' ? 2 : 3),
      pagePath = '/pages/makeAppointment/makeAppointment?detail=' + this.data.goodsId + (franchiseeId ? '&franchisee=' + franchiseeId : '') + ('&param=' + unitType)
    app.turnToPage(pagePath);
  },
  goodsCoverOnload: function(e){
    // var _this = this,
    //     originalWidth = e.detail.width,
    //     originalHeight = e.detail.height;

    // //获取图片的原始长宽
    // var windowWidth = 0;
    // var imageWidth = 0, imageHeight = 0;

    // wx.getSystemInfo({
    //   success: function (res) {
    //     windowWidth = res.windowWidth;
    //     imageWidth = windowWidth;
    //     imageHeight = imageWidth * originalHeight / originalWidth;
    //     _this.setData({
    //       goodsCoverWidth: imageWidth,
    //       goodsCoverHeight: imageHeight
    //     })
    //   }
    // })
  },
  modifyGoodsDetail: function(res){

    res.set('hot', res.hot+1);
    res.save();
    var _this = this,
        goods = res,
        isSeckill=goods.is_seckill,
        unitType = (goods.appointment_info && goods.appointment_info.unit_type) || '',
        description = goods.description,
        goodsModel = [],
        selectModels = [],
        modifySelectModels = '',
        modelStrs = {},
        price = 0,
        discountStr = '',
        allStock = 0,
        selectStock, selectPrice, selectModelId, matchResult, selectVirtualPrice, selectText = '', selectTitle, selectorginPrice=0,
        selectImgurl = '',
        appointment_desc,
        appointmentPhone; 
    var seckill_highPrice =0;
    var seckill_lowPrice = 0;
    var highPrice = 0;
    var lowPrice =0;
    goods.server_time = util.formatTime();
    goods.downCount = {
      hours: '00',
      minutes: '00',
      seconds: '00'
    };
    if (goods.seckill_start_state == 0) {
      _this.downcount = app.beforeSeckillDownCount(goods, _this, 'goods');
    } else if (goods.seckill_start_state == 1) {
      _this.downcount = app.duringSeckillDownCount(goods, _this, 'goods');
    }
   /*
    this.setData({
      unitType: unitType || '',
      appointmentDesc: goods.appointment_info && goods.appointment_info.appointment_desc ? goods.appointment_info.appointment_desc.replace(/<br \/>/g, "\r\n") : '更多优惠资讯详情请联系商家!',
      appointmentPhone: goods.appointment_info && goods.appointment_info.appointment_phone ? goods.appointment_info.appointment_phone:'',
      displayComment:goods.appointment_info &&  goods.appointment_info.display_comment == '1' ?goods.appointment_info.display_comment : ''
    });*/
    WxParse.wxParse('wxParseDescription', 'html', description, _this, 10);
/*
    for(var key in goods.model){
      if (!('1' in goods.model)) {
        delete goods.model[0];
      }
      if(key){
        var model = goods.model[key];
        goodsModel.push(model);
        if(model && model.subModelName){
          if (key == '1' && goods.goods_type == '1'){
            for(var index in model.subModelName){
              var adjustTime =  model.subModelName[index].split('-'),
              submodel = model.subModelName[index].substring(6,8),
              endHours = (submodel - 24) >= 10 ?  (submodel-24) : '0'+ (submodel - 24);
              model.subModelName[index] = submodel >= 24 ?  adjustTime[0] + '-' + '次日' + endHours + ':' + adjustTime[1].split(':')[1]  :adjustTime[0] +  '-当日' + adjustTime[1] ;
            }
          }
          if(goods.goods_type == '1' && model.id == '0'){
            for(var index in model.subModelName){
              model.subModelName[index] = model.subModelName[index] + (goods.appointment_info && goods.appointment_info.unit);
            }
          }
          modelStrs[model.id] = model.subModelName.join('、');
          selectModels.push(model.subModelId[0]);
          modifySelectModels = selectModels.toString();
          selectText += '“' + model.subModelName[0] + '” ';
        }

      }
    }*/
   
    if(goods.models){
      var goodsModelItems = goods.models;
      seckill_highPrice = goodsModelItems[0].models[0].seckill_price;
      seckill_lowPrice = goodsModelItems[0].models[0].seckill_price;
      highPrice = goodsModelItems[0].models[0].price;
      lowPrice = goodsModelItems[0].models[0].price;
      console.log(seckill_highPrice);
      for (var j = 0; j < goodsModelItems.length; j++) {
        var items = goodsModelItems[j].models;
      if(goods.is_seckill){ //假如是秒杀
        for (let i = 0; i < items.length; i++) {
       
          let seckill_price = +items[i].seckill_price;
          let modifyGoodsmodelseckill = items[i].model;
          seckill_highPrice = seckill_highPrice >= seckill_price ? seckill_highPrice : seckill_price;
          seckill_lowPrice = seckill_lowPrice <= seckill_price ? seckill_lowPrice : seckill_price;
          allStock += Number(items[i].seckill_stock);

          if (i == 0 && j == 0){
            selectPrice = items[i].seckill_price;
            selectStock = items[i].seckill_stock; 
            selectImgurl = items[0].img_url || goods.cover;
            selectorginPrice = items[0].price;
          }
        }
      }else{
        for (let i = 0; i < items.length; i++) {
          price = Number(items[i].price);
          //let virtual_price = Number(items[i].virtual_price);
          //let modifyGoodsmodel = items[i].model;
          highPrice = highPrice > price ? highPrice : price;
          lowPrice = lowPrice < price ? lowPrice : price;
         /*
          if ( virtual_price != 0){
            goods.virtual_highPrice = goods.virtual_highPrice ? (goods.virtual_highPrice > virtual_price ? goods.virtual_highPrice : virtual_price) : virtual_price;
          }*/
          allStock += Number(items[i].stock);
          if (i == 0 && j == 0) {
            selectPrice = items[0].price;
            selectStock = items[0].stock;
           // selectModelId = items[i].id;
            selectImgurl = items[i].img_url || goods.cover;
            selectorginPrice = items[0].price;
            //selectVirtualPrice = items[i].virtual_price;
          }
        }
      }
      selectModels = (goodsModelItems[0].models[0]);
   
    }
    } else {
      if (goods.is_seckill == 1) { //假如是秒杀
        selectPrice = goods.seckill_price;
        selectStock = goods.seckill_stock;
        allStock = goods.seckill_stock;
        selectorginPrice = goods.price;
      } else {
        selectPrice = goods.price;
        selectStock = goods.stock;
        selectorginPrice = goods.price;
        //  selectVirtualPrice = goods.virtual_price;
      }
      selectImgurl = goods.cover;
     
    }
    selectTitle = goods.title;
    //goods.model = goodsModel;
    if (Number(goods.max_can_use_integral) != 0 ) {
        discountStr = '（积分可抵扣' + (Number(goods.max_can_use_integral) / 100) + '元）';
    }
    if(goods.is_seckill == 1){
      goods.downCount = {
        hours : '00' ,
        minutes : '00' ,
        seconds : '00'
      };
      if(goods.seckill_start_state == 0){
        _this.downcount = app.beforeSeckillDownCount(goods , _this , 'goodsInfo');
      }else if(goods.seckill_start_state == 1){
        _this.downcount = app.duringSeckillDownCount(goods , _this , 'goodsInfo');
      }
    }
    selectText += '“' + goodsModelItems[0].submodelName + ':' + goodsModelItems[0].models[0].modelName + '” ';
    _this.setData({
      goodsInfo: goods,
     // modelStrs: modelStrs,
      'selectModelInfo.models': selectModels || '',
      'selectModelInfo.stock': selectStock || '',
      'selectModelInfo.price': selectPrice || '',
      'selectModelInfo.modelId': selectModelId || '',
      'selectModelInfo.models_text' : selectText || '',
      'selectModelInfo.imgurl' : selectImgurl || '',
      'selectModelInfo.virtualPrice': selectVirtualPrice || '',
      'selectModelInfo.subNameIndex': 0,
      'selectModelInfo.modelNameIndex': 0,
      'selectModelInfo.title': selectTitle,
      'selectModelInfo.orginPrice': selectorginPrice,
      allStock: allStock || '',
      isSeckill: isSeckill,
      seckill_lowPrice: seckill_lowPrice,
      seckill_highPrice: seckill_highPrice,
      lowPrice: lowPrice,
      highPrice: highPrice,
      priceDiscountStr: discountStr || '',
    })
    _this.getAssessList(0, 1);
  },
  showBuyDirectly: function(){
    if(this.data.isSeckill && this.data.goodsInfo.seckill_start_state != 1){
      app.showModal({content: '当前秒杀商品不在秒杀时间范围内，不能立即购买'});
      return ;
    }
    this.setData({
      addToShoppingCartHidden: false,
      ifAddToShoppingCart: false,
      imageOrVideo: 'image'
    })
  },
  showAddToShoppingCart: function(){
    if(this.data.isSeckill && this.data.goodsInfo.seckill_start_state == 2){
      app.showModal({content: '当前秒杀已结束，不能加入购物车'});
      return ;
    }
    this.setData({
      addToShoppingCartHidden: false,
      ifAddToShoppingCart: true,
      imageOrVideo: 'image'
    })
  },
  hiddeAddToShoppingCart: function(){
    this.setData({
      addToShoppingCartHidden: true
    })
  },
  selectSubModel: function (e) {
    var dataset = e.target.dataset,
      selectorginPrice = 0,
      submodelIndex = dataset.submodelIndex,
      modelIndex = dataset.modelIndex,
      data = {},
      selectModels = this.data.selectModelInfo.models,

      model = this.data.goodsInfo.models,
      text = '';
    selectorginPrice = model[submodelIndex].models[modelIndex].price;
    selectModels = model[submodelIndex].models[modelIndex];

    // console.log(selectModels)
    // 拼已选中规格文字
    text += '“' + model[submodelIndex].submodelName + ':' + model[submodelIndex].models[modelIndex].modelName+ '” ';

    data['selectModelInfo.models'] = selectModels;
    data['selectModelInfo.models_text'] = text;
    data['selectModelInfo.subNameIndex'] = submodelIndex;
    data['selectModelInfo.modelNameIndex'] = modelIndex;
    data['selectModelInfo.orginPrice'] = selectorginPrice;
    this.setData(data);
    this.resetSelectCountPrice();
  },
  resetSelectCountPrice: function () {
    var _this = this,
      selectModels = this.data.selectModelInfo.models,

      data = {};


    if (_this.data.isSeckill) {  //假如是秒杀
      data['selectModelInfo.stock'] = selectModels.seckill_stock;
      data['selectModelInfo.price'] = selectModels.seckill_price;
      //data['selectModelInfo.modelId'] = selectModels.id;
     // data['selectModelInfo.imgurl'] = selectModels.img_url;
    } else {
      data['selectModelInfo.stock'] = selectModels.stock;
      data['selectModelInfo.price'] = selectModels.price;
      //data['selectModelInfo.modelId'] = selectModels.id;
     // data['selectModelInfo.imgurl'] = selectModels.cover;
     // data['selectModelInfo.virtualPrice'] = selectModels.virtual_price;
    }



    this.setData(data);
  },
 
  
  
  clickMinusButton: function(e){
    var count = this.data.selectModelInfo.buyCount;

    if(count <= 1){
      return;
    }
    this.setData({
      'selectModelInfo.buyCount': count - 1
    });
  },
  clickPlusButton: function(e){
    var selectModelInfo = this.data.selectModelInfo,
        goodsInfo = this.data.goodsInfo,
        count = selectModelInfo.buyCount,
        stock = selectModelInfo.stock;

    if(count >= stock) {
      app.showModal({content: '购买数量不能大于库存'});
      return;
    }
    if(this.data.isSeckill && count >= goodsInfo.seckill_buy_limit){
      app.showModal({content: '购买数量不能大于秒杀限购数量'});
      return ;
    }
    this.setData({
      'selectModelInfo.buyCount': count + 1
    });
  },
  sureAddToShoppingCart: function () {
    var that = this;
    var goods_id = that.data.goodsId;
    var model_id = that.data.selectModelInfo.modelId || '';
    var objectId;

    var currentUser = Bmob.User.current();
    objectId = currentUser.id;


    var num = that.data.selectModelInfo.buyCount;
    var sub_shop_app_id = that.data.franchiseeId || '';
    var is_seckill = that.data.isSeckill ? 1 : 0;
    var price = that.data.selectModelInfo.price;
    var orginPrice = that.data.selectModelInfo.orginPrice;
    var title = that.data.selectModelInfo.title;
    var cover = that.data.selectModelInfo.imgurl;
    var subNameIndex = that.data.selectModelInfo.subNameIndex;
    var modelNameIndex = that.data.selectModelInfo.modelNameIndex;
    var ShoppingCarts = Bmob.Object.extend("shoppingCart");
    var Goods = Bmob.Object.extend("goods");
    var shoppingCart = new ShoppingCarts();
    var goods = new Goods();
    var isme = new Bmob.User();
    goods.id = goods_id
    isme.id = objectId;     //当前用户的objectId
    shoppingCart.set('models_text', that.data.selectModelInfo.models_text);
    shoppingCart.set("users", isme);
    shoppingCart.set("goods_id", goods_id);
    shoppingCart.set("num", num);
    shoppingCart.set("sub_shop_app_id", sub_shop_app_id);
    shoppingCart.set("is_seckill", is_seckill);
    shoppingCart.set("price", Number(price));
    shoppingCart.set("title", title);
    shoppingCart.set("cover", cover);
    shoppingCart.set("goodsInfo", goods);
    shoppingCart.set("subNameIndex", subNameIndex);
    shoppingCart.set("modelNameIndex", modelNameIndex);
   shoppingCart.set("original_price", Number(orginPrice));

    shoppingCart.save(null, {
      success: function (result) {
        // 添加成功，返回成功之后的objectId（注意：返回的属性名字是id，不是objectId），你还可以在Bmob的Web管理后台看到对应的数据
        app.showToast({
          title: '添加成功',
          icon: 'success'
        });
      },
      error: function (result, error) {
        // 添加失败
        console.log(error)
        app.showToast({
          title: '添加失败',
          icon: 'fail'
        });

      }
    });

  },
  
  buyDirectlyNextStep: function (e) {

    var that = this;
    var goods_id = that.data.goodsId;
    var model_id = that.data.selectModelInfo.modelId || '';
    var objectId;

    var currentUser = Bmob.User.current();
  
    objectId = currentUser.id;


    var num = that.data.selectModelInfo.buyCount;
    var sub_shop_app_id = that.data.franchiseeId || '';
    var is_seckill = that.data.isSeckill ? 1 : 0;
    var price = that.data.selectModelInfo.price;
    var title = that.data.selectModelInfo.title;
    var cover = that.data.selectModelInfo.imgurl;
    var subNameIndex = that.data.selectModelInfo.subNameIndex;
    var modelNameIndex = that.data.selectModelInfo.modelNameIndex;

    var ShoppingCarts = Bmob.Object.extend("shoppingCart");
    var Goods = Bmob.Object.extend("goods");
    var shoppingCart = new ShoppingCarts();
    var goods = new Goods();
    var isme = new Bmob.User();
    goods.id = goods_id
    isme.id = objectId;     //当前用户的objectId
    shoppingCart.set('models_text', that.data.selectModelInfo.models_text);
    shoppingCart.set("users", isme);
    shoppingCart.set("goods_id", goods_id);
    shoppingCart.set("num", num);
    shoppingCart.set("sub_shop_app_id", sub_shop_app_id);
    shoppingCart.set("is_seckill", is_seckill);
    shoppingCart.set("price", Number(price));
    shoppingCart.set("title", title);
    shoppingCart.set("cover", cover);
    shoppingCart.set("goodsInfo", goods);
    shoppingCart.set("subNameIndex", subNameIndex);
    shoppingCart.set("modelNameIndex", modelNameIndex);
   
    shoppingCart.save(null, {
      success: function (result) {
        // 添加成功，返回成功之后的objectId（注意：返回的属性名字是id，不是objectId），你还可以在Bmob的Web管理后台看到对应的数据
        /// console.log(result);

        var cart_arr = [result.id];

        var pagePath = '/pages/previewGoodsOrder/previewGoodsOrder?cart_arr=' + encodeURIComponent(cart_arr);

        that.hiddeAddToShoppingCart();
        app.turnToPage(pagePath, true);
      },
      error: function (result, error) {
        // 添加失败
        console.log(error)
        app.showToast({
          title: '添加失败',
          icon: 'fail'
        });

      }
    });


  },
  onShareAppMessage: function (res) {
    let that = this;
    let goodsInfo = this.data.goodsInfo;
    that.showCouponVerify();
    return {
      title: goodsInfo.title,
      path: '/pages/goodsDetail/goodsDetail?detail=' + that.data.goodsId,
      imageUrl: goodsInfo.img_urls ? goodsInfo.img_urls[0] : goodsInfo.cover,
    }
  },
  
  showQRCodeComponent:function(){
    let that = this;
    let goodsInfo = this.data.goodsInfo;
    let animation = wx.createAnimation({
      timingFunction: "ease",
      duration: 400,
    })
  
    var filePath = "";
    var img_url = goodsInfo.cover.replace(/b0.upaiyun/, "bmobcloud");
    img_url = img_url.replace(/http/, "https")
    // var filePath = "../../images/banner.jpg"
    //goodsInfo.img_urls ? goodsInfo.img_urls[0] : goodsInfo.cover;
    var text = goodsInfo.title;
    var id = goodsInfo.id,

      price = 76

    wx.downloadFile({
      url: img_url, //仅为示例，并非真实的资源
      success: function (res) {
        // 只要服务器有响应数据，就会把响应内容写入文件并进入 success 回调，业务需要自行判断是否下载到了想要的内容
        console.log(res);
        if (res.statusCode === 200) {

          filePath: res.tempFilePath

          that.get_qrcode(res.tempFilePath, text, price, id);
        }
      }
    })
    animation.bottom("0").step();
    that.setData({
      "pageQRCodeData.shareDialogShow": 0,
      "pageQRCodeData.shareMenuShow": true,
      "pageQRCodeData.page": that,

      "pageQRCodeData.animation": animation.export()
    })
    /*
    app.sendRequest({
      url: '/index.php?r=AppShop/ShareQRCode',
      data: {
        obj_id: that.data.goodsId,
        type: this.data.isSeckill ? 5 : 1,
        text: goodsInfo.title,
        price: (goodsInfo.highPrice > goodsInfo.lowPrice && goodsInfo.lowPrice != 0 ? (goodsInfo.lowPrice + ' ~ ' + goodsInfo.highPrice) : goodsInfo.price),
        goods_img: goodsInfo.img_urls ? goodsInfo.img_urls[0] : goodsInfo.cover,
        sub_shop_id: that.data.franchiseeId
      },
      success: function (res) {
        animation.bottom("0").step();
        that.setData({
          "pageQRCodeData.shareDialogShow": 0,
          "pageQRCodeData.shareMenuShow": true,
          "pageQRCodeData.imageUrl": res.data,
          "pageQRCodeData.animation": animation.export()
        })
      }
    })*/
  },
  showShareMenu: function(){
    app.showShareMenu();
  },
  makePhoneCall: function(){
    app.makePhoneCall(this.data.appointmentPhone);
  },
  hideShareMenu: function(){
    this.setData({
      hideShareMenu: true
    })
  },
  showPageCode: function(){

  },
  oneSelectDetailCommet: function(e){
    this.setData({
      detailCommetType: e.target.dataset.type
    })
  },
  getAssessList: function (commnetType1, page, append) {
    var that = this;
    var commnetType= commnetType1;
    console.log(commnetType);
    var commentNums=[0,0,0,0,0];
    var commentArr1=[];
    var commentArr2 = [];
    var commentArr3 = [];
    var commentArr4 = [];
    var AssessList = Bmob.Object.extend("AssessList");
    var assessList = new Bmob.Query(AssessList);
    
    assessList.equalTo("goods_id", that.data.goodsId);
    // 查询所有数据
    assessList.find({
      success: function (results) {
        console.log("共查询到 " + results.length + " 条记录");
        // 循环处理查询到的数据
        commentNums[0] = results.length;
        for (var i = 0; i < results.length; i++) {
          switch (results[i].get("level"))
         { case 1:
            commentNums[1] = commentNums[1]+1;
            commentArr1.push(results[i]);
            break;
            case 2:
              commentNums[2] = commentNums[2] + 1;
              commentArr2.push(results[i]);
              break;
            case 3:
              commentNums[3] = commentNums[3] + 1;
              commentArr3.push(results[i]);
             break;

        }
          if (results[i].get("img_arr").length>0)
           { commentNums[4] = commentNums[4]+1;
            commentArr4.push(results[i]);}
        }
        that.setData({
       
          commentNums: commentNums,
     
        
        })
        switch (commnetType)
        {
          case 0:
            that.setData({

              commentArr: results,

            })
            break;
          
          case 1:
          that.setData({

            commentArr: commentArr1,

          })
          break;
          case 2:
            that.setData({

              commentArr: commentArr2,

            })
            break;
          case 3:
            that.setData({

              commentArr: commentArr3,

            })
            break;
          case 4:
            that.setData({

              commentArr: commentArr4,

            })
            break;
      
        }
      },
      error: function (error) {
        console.log("查询失败: " + error.code + " " + error.message);
      }
    });
    /*
    app.getAssessList({
      method: 'post',
      data: {
        goods_id: that.data.goodsId,
        idx_arr: {
          idx: 'level',
          idx_value: commnetType
        },
        page: page,
        page_size: 20,
        sub_shop_app_id: this.data.franchiseeId
      },
      success: function (res) {
        var commentData = res.data;
        if (append) {
          commentData = that.data.commentArr.concat(commentData);
        }
        that.setData({
          commentArr: commentData,
          commentNums: res.num,
          commentPage: that.data.commentPage + 1,
          commentExample: res.data[0] || '',
          commentTotalPage: res.total_page,
          displayComment: that.data.goodsInfo.goods_type === '0' ? (+res.num[0] > 0 ? false : true) : (that.data.goodsInfo.appointment_info && that.data.goodsInfo.appointment_info.display_comment == '1' ? that.data.goodsInfo.appointment_info.display_comment : '')
        })
      }
    });*/
  },
  clickCommentLabel: function (e) {
    var commentType = e.target.dataset.type,
      data = {};
    data.commentPage = 1;
    data.commnetType = commentType;
    this.setData(data);
    this.getAssessList(commentType, 1);
  },
  clickPlusImages: function (e) {
    app.previewImage({
      current: e.currentTarget.dataset.src,
      urls: e.currentTarget.dataset.srcarr
    })
  },
  carouselIndex: function (event){
    this.setData({
      carouselCurrentIndex: event.detail.current + 1     
    })
  },
  toCouponList: function (e){
    
   var franchiseeId=e.currentTarget.dataset.franchisee;
    app.turnToPage('../couponReceiveListPage/couponReceiveListPage?franchiseeId=' + franchiseeId, true);
  },
  changeImageOrVideo: function(event){
    this.setData({
      imageOrVideo: event.currentTarget.dataset.type
    })
  },
  toRecommendGoodsDetail: function(event){
    app.turnToGoodsDetail(event);
  },
  startPlayVideo: function(){
    this.videoContext.play();
    this.setData({
      videoPlay: true
    })
  },
  pausePlayVideo: function() {
    this.setData({
      videoPlay: false
    })
  }
})
